package com.example.springdemo;
import cn.gov.zcy.open.sdk.http.ResponseResult;
import cn.gov.zcy.open.sdk.http.util.VersionInfoUtils;
import cn.gov.zcy.open.sdk.open.HttpMethod;
import cn.gov.zcy.open.sdk.open.ZcyClient;
import cn.gov.zcy.open.sdk.open.ZcyOpenRequest;
import cn.gov.zcy.open.sdk.open.util.StringUtils;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author PL
 * @create 2024/4/7 12:49
 * @Desc
 */
public class HisQuanShangDemo {
    //test环境
    static String API_TEST_YMG = "https://convenient.wsjkw.zj.gov.cn/test/open/api";
    /** 政采云开放平台分配的appkey Todo 替换使用用户自己的appkey */
//	static String APP_KEY = "申请的key";
//	static String pkcs8PrivateKey = "-----BEGIN PRIVATE KEY----- 替换申请的秘钥 -----END PRIVATE KEY-----";

    static String APP_KEY = "248010143";
    static String pkcs8PrivateKey = "-----BEGIN PRIVATE KEY-----\n" +
            "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALu5FfydHzwGgcZY\n" +
            "dz9A6P7FYWqPoUcBj7WKxEs0gz2D8U9YZ9x/JL8Ot2hej8ZBGyXU0J3PShB+3WoA\n" +
            "M/ieFdvLj9bLnfmUfOPXmMdl69daQJ7iyNTMPZc8Ebsoc74oYUoBABF1oKhRPcwZ\n" +
            "az1sc/aUSegpxGHYqpM6jCJSwWMxAgMBAAECgYEAloAW7oYRipA07w3x3JZvtgIM\n" +
            "zeAFDuZjjsqIATtClMj5aAGakx6kGUD1LgnR/sInv7bU4hBUctEjNl6fTA2Bu2lm\n" +
            "2447WWRPnx4Vrx6Sel268PaVjlgRe/eCEM7IIW73LGiKcfPJI0y5E8WtHnEw+a8c\n" +
            "gIagBVu3YhIaVQGuWLkCQQD3iuyphPF/+jbnwgn5qIRNg3u5AyIpL0A8i6gztdU7\n" +
            "m3/iwvDS1+hWfLYK/6GDvECqI6U0D+K2hG+Vg3X3CCKnAkEAwiL2U/7SCc5TVjsk\n" +
            "bAL3cxvraC8NPnGqjZmA0nSwIMvGl4uCscuXDYy54O2j42teBJ/lLqFZPOxp0WOn\n" +
            "LxE+ZwJAEUEFresuShVOrmi/+T7dueloPkURpH0+pPm3B6Os8TKtf0jHMGsMLrsS\n" +
            "lUGsKFp+x10krrRMwRwKCwnWtxlCEQJAeOs16pNpV9o/ZhJoWS5v2i6lrbrA0QgT\n" +
            "ZycZafxsR8Ek7PdkbEGW0EW68TKTRe92HANLyIOPBbdrIZSkaVigOQJBAKibJv1W\n" +
            "VWKvwLIPlo42OpCrDptsYwlpXVAmWaXcF7n4uS2TL46LF2Jp7/ErC1wuZ5jGm41E\n" +
            "pNaW91gHvmFTn/o=\n" +
            "-----END PRIVATE KEY-----";


    public static void main(String[] args) throws Exception {
        ZcyClient zcyClient = new ZcyClient();
        //请求信息
        ZcyOpenRequest request = getReq();
//		构建header参数
        try {
            Map<String, String> jwtHeaders = new HashMap<String, String>();
            jwtHeaders.put("version", "1.0.0");
            request.setHeaderMap(jwtHeaders);
            System.out.println("==========入参=========");
            System.out.println(JSONObject.toJSONString(request));
            ResponseResult result = zcyClient.sendRequest(request);
            System.out.println("========返回结果=========");
            System.out.println(result.getBody());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Map<String, String> buildCommonHeaders(ZcyOpenRequest request, String contentType) {
        /*组装系统级Header Key-Value*/
        Map<String, String> headers = null == request.getHeaderMap() ? new HashMap<>() : request.getHeaderMap();
        headers.put("Content-Type", contentType);
        headers.put("Accept", "application/json");
        headers.put("zcy-open-sdk-version", VersionInfoUtils.getSdkVersion());
        headers.put("X-Ca-Timestamp", String.valueOf(System.currentTimeMillis()));
        headers.put("X-Ca-Key", request.getAppKey());
        headers.put("X-Ca-Format", "json2");
        if (StringUtils.isNotBlank(request.getToken())) {
            headers.put("token", request.getToken());
        }
        if (StringUtils.isNotBlank(request.getIp())) {
            headers.put("X-Forwarded-For", request.getIp());
        }
        if (StringUtils.isNotBlank(request.getEnv())) {
            headers.put("env", request.getEnv());
        }
        return headers;
    }

    public static ZcyOpenRequest getReq(){
        //调用jwt构造方法生成request
        ZcyOpenRequest request = ZcyOpenRequest.buildJwtRequest(APP_KEY, pkcs8PrivateKey, true, API_TEST_YMG);
        request.setMethod(HttpMethod.POST);

        //构建业务参数
//		request.setUri("/zcy.vaccine.his.dog.additional.sync");
//		HisDogAdditionalUploadDto data = getDogData(123L);

        request.setUri("/zcy.vaccine.his.obstetrics.archives.create");
        HisObstetricsUploadDto data = getChildData(123L);

        Map<String, Object> paramMaps = BeanUtil.beanToMap(data);
//        Map<String, Object> paramMaps1 = paramMaps.entrySet().stream().filter(entry ->Objects.isNull(entry.getValue())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
//        paramMaps.entrySet().stream().map(entry ->)
        List<String> collect = paramMaps.keySet().stream().filter(t -> Objects.isNull(paramMaps.get(t))).collect(Collectors.toList());
        for (String key : collect) {
            paramMaps.remove(key);
        }
        request.setParamMap(paramMaps);
        return request;
    }

    private static HisObstetricsUploadDto getChildData(Long orgId) {
        HisObstetricsUploadDto dto = new HisObstetricsUploadDto();
        dto.setHisChildCode("123456789");
        dto.setOrgId(orgId);
        dto.setSyncStatus(1);
        dto.setElectronicHealthCard("electronicHealthCard");
        dto.setMediaIdentificationCode("1");
        dto.setBornMedicalCertificateCode("1");
        dto.setName("name");
        dto.setSex(5);
        dto.setBirthday("2024-01-01 00:00:00");
        dto.setBornWeight(1);
        dto.setGestationalCount(1);
        dto.setNationality("nationality");
        dto.setNationCode("1");
        dto.setHouseholdStreetCode("1");
        dto.setHouseholdAddress("householdAddress");
        dto.setFamilyStreetCode("1");
        dto.setFamilyAddress("familyAddress");
        dto.setMotherName("motherName");
        dto.setMotherIdType("01");
        dto.setMotherIdCard("motherIdCard");
        dto.setMotherMobile("motherMobile");
        dto.setMotherHbsAg("1");
        dto.setFatherName("fatherName");
        dto.setFatherIdType("01");
        dto.setFatherIdCard("fatherIdCard");
        dto.setFatherMobile("fatherMobile");
        dto.setApgarScore(1);
        dto.setModifyUser("modifyUser");
        dto.setWristbandNo("wristbandNo");
        dto.setHospitalizedNo("hospitalizedNo");
        dto.setBedNo("bedNo");
        dto.setWardNo("wardNo");
        dto.setGestationalAge(222);
        return dto;
    }

    private static HisDogAdditionalUploadDto getDogData(Long orgId) {
        HisDogAdditionalUploadDto dto = new HisDogAdditionalUploadDto();
        dto.setOrgId(orgId);
        dto.setName("name");
        dto.setSex(1);
        dto.setBirthday("2024-01-01 00:00:00");
        dto.setIdType("1");
        dto.setIdCard("idCard");
        dto.setMedicalRecordNo("medicalRecordNo");
        dto.setDogAdditionalId("dogAdditionalId");
        dto.setExposedType(3);
        dto.setExposedPeriod(1);
        dto.setExposedTime("2024-01-01 00:00:00");
        dto.setExposedLevel(1);
        dto.setExposedParts(1);
        dto.setExposedWay(1);
        dto.setExposedStreetCode("1");
        dto.setExposedAddress("1");
//		dto.setWoundTreatment(1);
        dto.setUsage("1");
        dto.setDosage(1);
        dto.setWeight(1);
        dto.setAnimalType(1);
        dto.setAnimalImmunity(1);
        dto.setHurtMany(1);
        dto.setNeedVaccinate(1);
        dto.setAgreeVaccinate(1);
        dto.setProgramCode("1");
        dto.setRegisterName("registerName");
        dto.setRegisterTime("2024-01-01 00:00:00");
        dto.setRegisterDeptName("registerDeptName");
        return dto;
    }

    @Data
    public static class HisDogAdditionalUploadDto  implements Serializable {
        /**
         * 机构ID
         * 必填，由政采云提供，鉴权使用
         */
        private Long orgId;
        /**
         * 受种者姓名
         * 必填
         */
        private String name;
        /**
         * 性别
         * 必填；0未知性别；1男；2女；9未说明性别
         */
        private Integer sex;
        /**
         * 出生时间
         * 必填;格式：yyyy-MM-dd hh:mm:ss
         */
        private String birthday;
        /**
         * 证件类型
         * 必填
         */
        private String idType;
        /**
         * 证件号
         * 必填
         */
        private String idCard;
        /**
         * 病案号
         * 必填
         */
        private String medicalRecordNo;
        /**
         * 附加信息唯一ID
         * 必填
         */
        private String dogAdditionalId;
        /**
         * 暴露类型
         * 必填；1暴露前；2加强免疫；3暴露后；4其他；5仅破伤风
         */
        private Integer exposedType;
        /**
         * 暴露后时间范围
         * 必填；1：首次暴露，2:全程免疫，3:全程接种三个月及三个月以上暴露，4:接种期间再次暴露
         */
        private Integer exposedPeriod;
        /**
         * 暴露时间
         * 必填；格式：yyyy-MM-dd hh:mm:ss
         */
        private String exposedTime;
        /**
         * 暴露等级
         * 必填；1 I级；2 II级；3 III级
         */
        private Integer exposedLevel;
        /**
         * 暴露部位
         * 必填；1：上肢，2：下肢，3：躯干，4：头颈部，5：其他，多个逗号拼接
         */
        private Integer exposedParts;
        /**
         * 暴露方式
         * 必填 1咬伤；2抓伤；3皮损伤口或舔膜舔舐；4其他
         */
        private Integer exposedWay;
        /**
         * 暴露地址街道编码
         * 必填
         */
        private String exposedStreetCode;
        /**
         * 暴露详细地址
         * 必填
         */
        private String exposedAddress;
        /**
         * 伤口处置
         * 必填；1 自行处理；2门诊处理；3未作处理；多个逗号分隔
         */
        private Integer woundTreatment;
        /**
         * 被动免疫制剂使用情况
         * 若母亲乙肝表面抗原为阳性，必填。
         */
        private String usage;
        /**
         * 使用剂量
         * 必填；1未用；2免疫蛋白球；3血清；4单克隆抗体；5其他
         */
        private Integer dosage;
        /**
         * 体重
         * 必填
         */
        private Integer weight;
        /**
         * 伤人动物种类
         * 必填；单位：g
         */
        private Integer animalType;
        /**
         * 伤人动物免疫史
         * 必填；1狗；2猫；3其他
         */
        private Integer animalImmunity;
        /**
         * 是否一犬伤多人
         * 必填；0无；1有；2不详
         */
        private Integer hurtMany;
        /**
         * 是否需要接种
         * 必填；0否；1是；2不详
         */
        private Integer needVaccinate;
        /**
         * 是否同意接种
         * 必填；0：否，1：是
         */
        private Integer agreeVaccinate;
        /**
         * 接种程序方案
         * 必填；0-7-21,0-7-28,2-1-1,0-3-7-14-28,0-3,0-3-7,0 一针法,customer 自定义
         */
        private String programCode;
        /**
         * 登记人
         * 必填
         */
        private String registerName;
        /**
         * 登记时间
         * 必填；格式：yyyy-MM-dd hh:mm:ss
         */
        private String registerTime;
        /**
         * 登记单位名称
         * 必填
         */
        private String registerDeptName;
    }

    @Data
    public static class HisObstetricsUploadDto implements Serializable {
        /**
         * his个案唯一标识
         * 必填
         */
        private String hisChildCode;
        /**
         * 机构ID
         * 必填，由政采云提供，鉴权使用
         */
        private Long orgId;
        /**
         * 同步状态
         * 必填；0 新增；1 更新；2 删除
         */
        private Integer syncStatus;
        /**
         * 健康卡号
         * 非必填
         */
        private String electronicHealthCard;
        /**
         * 个案信息介质识别码
         * 非必填
         */
        private String mediaIdentificationCode;
        /**
         * 出生医学证明编号
         * 非必填
         */
        private String bornMedicalCertificateCode;
        /**
         * 受种者姓名
         * 必填
         */
        private String name;
        /**
         * 性别
         * 必填；0未知性别；1男；2女；9未说明性别
         */
        private Integer sex;
        /**
         * 出生时间
         * 必填 格式：yyyy-MM-dd hh:mm:ss
         */
        private String birthday;
        /**
         * 出生体重
         * 必填；单位:g
         */
        private Integer bornWeight;
        /**
         * 胎次
         * 必填；范围：1-10
         */
        private Integer gestationalCount;
        /**
         * 国籍
         * 必填 参照 GB/T 2659-2000国籍代码
         */
        private String nationality;
        /**
         * 民族
         * 必填 GB/T 3304 根据具体民族取值
         */
        private String nationCode;
        /**
         * 户籍县编码
         * 必填；街道纬度
         */
        private String householdStreetCode;
        /**
         * 户籍地址
         * 必填
         */
        private String householdAddress;
        /**
         * 现住地区编码
         * 必填
         */
        private String familyStreetCode;
        /**
         * 居住地址
         * 必填
         */
        private String familyAddress;
        /**
         * 母亲姓名
         * 必填
         */
        private String motherName;
        /**
         * 母亲证件类型
         * 必填 参照  WS364.3 CV02.01.101身份证件类别代码
         */
        private String motherIdType;
        /**
         * 母亲证件号码
         * 必填
         */
        private String motherIdCard;
        /**
         * 母亲电话
         * 必填
         */
        private String motherMobile;
        /**
         * 母亲乙肝表面抗原
         * 必填；母亲HbsAg是否阳性 01、阳性 02、阴性 03、未检测
         */
        private String motherHbsAg;
        /**
         * 父亲姓名
         * 参照 WS364.3 CV02.01.101身份证件类别代码
         */
        private String fatherName;
        /**
         * 父亲证件类型
         * 新增字段。
         */
        private String fatherIdType;
        /**
         * 父亲证件号码
         * 新增字段。
         */
        private String fatherIdCard;
        /**
         * 父亲电话
         */
        private String fatherMobile;
        /**
         * 新生儿APgar评分
         */
        private Integer apgarScore;
        /**
         * 更新人员
         */
        private String modifyUser;
        /**
         * 新生儿腕带号
         */
        private String wristbandNo;
        /**
         * 住院号
         */
        private String hospitalizedNo;
        /**
         * 床位号
         */
        private String bedNo;
        /**
         * 病区
         */
        private String wardNo;

        private Integer gestationalAge;
    }
}
